package com.cictec.middleware.tde.rm.mina.filter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.PropertiesUtils;
import com.cictec.middleware.tde.rm.SessionManager;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x80PlatformMessage;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0xCAPlatformMessage;

@Component
public class AuthenticationFilter extends IoFilterAdapter {

	private static Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);

	@Autowired
	private SessionManager sessionManager;
	/**
	 * 鉴权消息ID
	 */
	private Set<Integer> allowedMessages;

	private List<String> notAllowedDevCode = new ArrayList<String>();

	public AuthenticationFilter(){
		
		Set<Integer> allowedMessages = new HashSet<Integer>();
		allowedMessages.add(0X01);
		allowedMessages.add(0X4A);
		allowedMessages.add(0X08);
		setAllowedMessages(allowedMessages);
		
		if(logger.isDebugEnabled()){
			String str = null;
			for (Integer integer : allowedMessages) {
				String messageId = PMSUtils.addZeroLForString(String.valueOf(Integer.toHexString(integer)), 2);
				str = str == null ? "0x"+messageId : str + ",0x"+messageId;
			}
			if(str != null){
				logger.debug("【AuthenticationFilter】【锐明】 设置允许未经验证直接访问服务器的指令集 {}", str);
			}
		}
	}
	
	@PostConstruct
	public void init() {

		String notDevCode = PropertiesUtils.getString("system.parameter.notAllowedDevCode");
		if (!PMSUtils.isEmpty(notDevCode)) {
			String[] arr = notDevCode.split(",");
			notAllowedDevCode = Arrays.asList(arr);

			logger.debug("【AuthenticationFilter】【锐明】 设置不允许访问服务器的设备编号集合 {}", allowedMessages);
		}
	}

	/**
	 * 
	 */
	@Override
	public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {

		TerminalMessage tm = (TerminalMessage) message;
		if (notAllowedDevCode.contains(tm.getTerminalId())) {
			session.closeNow();
			logger.warn("未授权的终端 {}", tm.getTerminalId());
		}

		if (sessionManager.isAuthenticated(session) || allowedMessages.contains(tm.getMessageId())) {
			super.messageReceived(nextFilter, session, message);
		} else {
			// session.close(true);
			session.closeNow();
			logger.warn("未授权的终端访问 地址 {} 消息ID {} ", session.getRemoteAddress().toString(),
					Integer.toHexString(tm.getMessageId()));
		}

	}

	@Override
	public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
		TerminalMessage tm = (TerminalMessage) writeRequest.getMessage();
		if (!sessionManager.isAuthenticated(session)) {
			// 终端还没有通过鉴权

			switch (tm.getMessageId()) {
			case 0xca: {
				// 获取编号应答
				Rm0xCAPlatformMessage pir = (Rm0xCAPlatformMessage) tm;
				if (pir.getId() == -1) {
					// session.close(true);
					session.closeNow();
				} else {
					super.messageSent(nextFilter, session, writeRequest);
				}

				break;
			}
			default: {
				super.messageSent(nextFilter, session, writeRequest);
			}
			}
		}
	}


	public Set<Integer> getAllowedMessages() {
		return allowedMessages;
	}

	public void setAllowedMessages(Set<Integer> allowedMessages) {
		this.allowedMessages = allowedMessages;
	}

}
